from abc import ABCMeta, abstractmethod

"""
角色：
    抽象策略（Strategy）
    具体策略（ConcreteStrategy）
    上下文（Context）
"""


# 抽象策略
class Strategy(metaclass=ABCMeta):
    @abstractmethod
    def execute(self, data):
        pass


# 具体策略
class FastStrategy(Strategy):
    def execute(self, data):
        print(f"用时较快的策略{data}")


# 具体策略
class SlowStrategy(Strategy):
    def execute(self, data):
        print(f"用时较慢的策略{data}")


# 上下文
class Context:
    def __init__(self, strategy, data):
        self.strategy = strategy
        self.data = data

    def set_strategy(self, strategy):
        self.strategy = strategy

    def do_strategy(self):
        self.strategy.execute(self.data)


# client
data = "123456"
s1 = FastStrategy()
s2 = SlowStrategy()
context = Context(s1, data)
context.do_strategy()

context.set_strategy(s2)
context.do_strategy()


import types



class People:

    def __init__(self, func=None):
        if func:
            #把方法绑定到类的实例中,此时方法在类实例间不共享
            #python 万物皆对象
            self.speak = types.MethodType(func, self)

    def speak(self):
        print("说中文")


def speak_english(self):
    print('说英语')


def speak_german(self):
    print('说德语')


if __name__ == '__main__':
    test1 = People()
    test2 = People(speak_english)
    test3 = People(speak_german)
    [func.speak() for func in [test1, test2, test3]]